package com.zqwh.xtool.activity;

import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.Display;
import android.widget.TextView;

import com.zqwh.xtool.R;
import com.zqwh.xtool.ToolsApp;
import com.zqwh.xtool.domain.DeviceConfigVO;
import com.zqwh.xtool.profile.ProfileRpCabinetZzMetro;
import com.zqwh.xtool.profile.ProfileWislinkCabinet;
import com.zqwh.xtool.service.HeartbeatService;
import com.zqwh.yj.sdk.model.InventoryListener;
import com.zqwh.yj.sdk.model.RfidGx16ModelImpl;
import com.zqwh.yj.sdk.utils.DeviceUtils;
import com.zqwh.yj.sdk.utils.LogUtils;
import com.zqwh.yj.sdk.utils.NetworkUtils;
import com.zqwh.yj.sdk.utils.SerialPortUtils;
import com.zqwh.yj.sdk.utils.StringUtils;
import com.zqwh.yj.sdk.utils.ToastUtils;
import com.zqwh.yj.sdk.utils.httpRequest.subscribers.NetCallback;

import java.util.ArrayList;
import java.util.List;

import android_serialport_api.SerialPort;

import static com.zqwh.xtool.ToolsApp.gContext;
import static com.zqwh.xtool.ToolsApp.gDevNo;
import static com.zqwh.xtool.ToolsApp.gDeviceModel;
import static com.zqwh.xtool.ToolsApp.gNFCModel;
import static com.zqwh.xtool.ToolsApp.gProfile;
import static com.zqwh.xtool.ToolsApp.gRfidModel;


/**
 * 开机初始化页面
 * 初始化RFID模块，电子锁，指静脉等硬件设备
 * Created by eason.yang on 2019/7/4.
 */

public class InitActivity extends BaseActivity{
    private static final String MODULE_NETWORK = "NETWORKS";
    private static final String MODULE_RFID = "RFID";
    private static final String MODULE_ACTIVATED = "ACTIVATED";
    private static final String MODULE_NFC = "NFC";
    private static final String MODULE_INVENTORY = "INVENTORY";

    private TextView tvInitLog;
    private List<SysInitOption> sysInitOptions;

    class SysInitOption{
        String module;
        int result;
        String reason;
        boolean confirm;

        SysInitOption(String module, int result, String reason, boolean confirm) {
            this.module = module;
            this.result = result;
            this.reason = reason;
            this.confirm = confirm;
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Display display = getWindowManager().getDefaultDisplay();
        Point point = new Point();
        display.getSize(point);
        int width = point.x;
        int height = point.y;
        LogUtils.logout("Screen width  : "+width);
        LogUtils.logout("Screen height : "+height);
        LogUtils.logout("Device sn is : "+DeviceUtils.getSN());


        setContentView(R.layout.activity_initialization_box);

        if (width > height) {
            setView();
            initSysInitOptions();

            checkNetwork();
            startHeartbeat();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    private void startHeartbeat() {
        startService(new Intent(gContext, HeartbeatService.class));
    }

    private void setView() {
        tvInitLog = findViewById(R.id.tv_init_log);
    }

    private void initSysInitOptions() {
        sysInitOptions = new ArrayList<>();
        sysInitOptions.add(new SysInitOption(MODULE_NETWORK, -1, null, true));
        sysInitOptions.add(new SysInitOption(MODULE_RFID, -1, null, true));
        sysInitOptions.add(new SysInitOption(MODULE_NFC, -1, null, true));
        sysInitOptions.add(new SysInitOption(MODULE_ACTIVATED, -1, null, true));
        sysInitOptions.add(new SysInitOption(MODULE_INVENTORY, -1, null, true));
    }

    private void setOptionsAndCheck(String module, int result, final String reason){
        for (SysInitOption option:sysInitOptions){
            if (module.equals(option.module)){
                option.result = result;
                option.reason = reason;
                LogUtils.logout(reason);
                addInitLog(reason);
            }
        }
        for (SysInitOption option : sysInitOptions){
            if (option.confirm && option.result != 0){
                return;
            }
        }
        startActivity(new Intent(this, LoginActivity.class));
        finish();
    }

    private void checkNetwork() {
        boolean available = NetworkUtils.isNetworkAvailable(gContext);
        if (available){
            setOptionsAndCheck(MODULE_NETWORK, 0, "【OK】设备联网正常");
            initRFID();
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    checkNetwork();
                }
            }, 2000);
        }
    }

    private void initNFC() {
        gNFCModel = new SerialPortUtils();
        SerialPort serialPort = gNFCModel.openSerialPort("read-card", gProfile.getNFC_UART_PATH(), gProfile.getNFC_BAUD_RATE());
        if (serialPort != null) {
            setOptionsAndCheck(MODULE_NFC, 0, "【OK】初始化刷卡模块成功");
        }else {
            setOptionsAndCheck(MODULE_NFC, 1, "【FAIL】初始化刷卡模块失败");
        }
    }

    private void initRFID() {
        gDeviceModel.activated(DeviceUtils.getSN(), new NetCallback<DeviceConfigVO>() {
            @Override
            public void onSuccess(DeviceConfigVO deviceConfigVO) {
                setOptionsAndCheck(MODULE_ACTIVATED, 0, "【OK】设备已激活，SN = "+DeviceUtils.getSN());
                ToolsApp.setDevId(deviceConfigVO.getDevId());
                LogUtils.logout("Device id : "+deviceConfigVO.getDevId());
                LogUtils.logout("deviceConfigVO: "+deviceConfigVO.toString());
                if (!StringUtils.isEmpty(deviceConfigVO.getDevNo())) {
                    gDevNo = deviceConfigVO.getDevNo();
                }
                LogUtils.logout("Device NO : "+gDevNo);

                if (!StringUtils.isEmpty(deviceConfigVO.getProfile())) {
                    LogUtils.logout("Device profile : "+deviceConfigVO.getProfile());
                    setProfile(deviceConfigVO.getProfile());
                }

                if (deviceConfigVO.getRfidAntNumber() != null && deviceConfigVO.getRfidAntNumber() != 0) {
                    gProfile.setRFID_ANT_NUMBER(deviceConfigVO.getRfidAntNumber());
                }

                if (deviceConfigVO.getRfidPower() != null && deviceConfigVO.getRfidPower() != 0) {
                    gProfile.setRFID_POWER(deviceConfigVO.getRfidPower());
                }
                LogUtils.logout("RFID power : "+deviceConfigVO.getRfidPower());

                if (deviceConfigVO.getRfidInventoryDuration() != null && deviceConfigVO.getRfidInventoryDuration() != 0) {
                    gProfile.setRFID_INVENTORY_TIME(deviceConfigVO.getRfidInventoryDuration());
                }
                LogUtils.logout("RFID inventory duration : "+deviceConfigVO.getRfidInventoryDuration());

                gRfidModel = new RfidGx16ModelImpl(gProfile.getRFID_MAX_ANT_NUMBER(),
                                                    gProfile.getRFID_ANT_NUMBER(),
                                                    gProfile.getRFID_UART_PATH(),
                                                    gProfile.getRFID_BAUD_RATE(),
                                                    gProfile.getRFID_POWER());

                int ret = gRfidModel.connectSerialPort();
                if (ret < 0){
                    setOptionsAndCheck(MODULE_RFID, 1, "【FAIL】初始化RFID模块失败");
                    LogUtils.error("RFID module connect failed");
                } else {
                    setOptionsAndCheck(MODULE_RFID, 0, "【OK】初始化RFID模块成功");
                    LogUtils.logout("RFID module connect successful");
                    startInventoryTag();
                }

                if (gProfile.isUSE_NFC()){
                    initNFC();
                }

                lock();
            }

            @Override
            public void onError(String msg) {
                LogUtils.logout(msg);
                LogUtils.error("Device failed to start");
                setOptionsAndCheck(MODULE_ACTIVATED, 1, "【FAIL】设备未激活，SN = "+DeviceUtils.getSN());
            }
        });
    }

    private void setProfile(String profile) {
        gProfile = new ProfileRpCabinetZzMetro();
        if (profile.equals("RP_CABINET_ZZ_METRO")){
            gProfile = new ProfileRpCabinetZzMetro();
        } else if (profile.equals("WISLINK_CABINET")){
            gProfile = new ProfileWislinkCabinet();
        }
    }

    private void startInventoryTag(){
        gRfidModel.startInventoryTag(gProfile.getRFID_INVENTORY_TIME(), new InventoryListener() {
            @Override
            public void onInventoryTagFinish(List<String> lsTagList) {
                setOptionsAndCheck(MODULE_INVENTORY, 0, "【OK】RFID标签盘点完成, 初始标签数"+lsTagList.size());
            }

            @Override
            public void onInventoryChanged(final int tagCount, final String epc, int antId) {
            }

            @Override
            public void onInventoryOnce(String epc, int antId) {

            }

            @Override
            public void onInventoryTick(int tickCount, final int tagCount) {
            }

            @Override
            public void onInventoryError(String errMsg) {
                ToastUtils.showLongToast(gContext, errMsg);
            }
        });
    }

    private void addInitLog(final String content){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvInitLog.setText(tvInitLog.getText().toString()+"\n"+content);
            }
        });
    }
}
